import React, { Component } from 'react'
import { inject, observer } from 'mobx-react';
import { Toast, ListView, Picker, Flex, SegmentedControl, List, Button, Popup, Icon, DatePicker, TextareaItem, InputItem, Stepper, ImagePicker } from 'antd-mobile'
import { hashHistory } from 'react-router'
import { createForm } from 'rc-form';
import Ajax from 'lib/Ajax';
import { backUrl } from 'lib/fun';

const Item = List.Item;

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let maskProps;
if (isIPhone) {
  // Note: the popup content will not scroll.
  maskProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

function getBody(xhr) {
  const text = xhr.responseText || xhr.response;
  if (!text) {
    return text;
  }

  try {
    return JSON.parse(text);
  } catch (e) {
    return text;
  }
}

@inject('appStore', 'languageStore')
@observer
class ModuleName extends Component {
	constructor(props) {
    super(props);
    this.state = {

    }
  }

  componentDidMount(){
    this.props.appStore.checkIsLogined();
  }

  fun = () => {

  }

  buy = ()=>{
    const { imgBaseUrl, userData } = this.props.appStore;
    Popup.show(<div>
      <BuyModule
        onClose={this.onClose}
        userData={userData}
        imgBaseUrl={imgBaseUrl}
      />
    </div>, { animationType: 'slide-up', maskProps, maskClosable: false });
  };

  onClose = (obj) => {
    Popup.hide();
    if(obj){
      this.props.appStore.updataUserData(obj);
    }
  };

  render() {
    const { imgBaseUrl, userData } = this.props.appStore;
    return (
    	<div className="zone">
        <div className="top">
          <div className="img">
            <img src={`${imgBaseUrl}${userData.img||userData.coverImg}`} alt=""/>
          </div>
          <div className="center">
            <h3>{userData.nickname}</h3>
            <p>注册于:{userData.createTime}</p>
          </div>
          <a href="javascript:;" className="setting" onClick={()=>{
            this.buy()
          }}><i className="iconfont icon-setting1"></i></a>
        </div>
        {
          this.props.appStore.isTeacher?"":<List className="my-list">
            <Item thumb={<i className="iconfont icon-wenda"></i>} arrow="horizontal" onClick={() => {
              hashHistory.push('/zone/question');
            }}>我的问答</Item>
            <Item thumb={<i className="iconfont icon-jihua"></i>} arrow="horizontal" onClick={() => {
              hashHistory.push('/zone/plan');
            }}>我的计划</Item>
            <Item thumb={<i className="iconfont icon-laoshi"></i>} arrow="horizontal" onClick={() => {
              hashHistory.push('/zone/teacher');
            }}>我的导师</Item>
            <Item thumb={<i className="iconfont icon-mianshi"></i>} arrow="horizontal" onClick={() => {
              hashHistory.push('/zone/interview');
            }}>我的面试服务</Item>
          </List>
        }
    	</div>
    )
  }
}

module.exports = ModuleName

class buyModuleComp extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      file: props.userData.img||props.userData.coverImg||"",
      files: [{
        url: props.userData.img||props.userData.coverImg||"",
        id: 1111
      }]
    }
  }

  submit = () => {
    const self = this;
    const { userId } = this.props.userData;
    const option = self.props.form.getFieldsValue();
    const obj = Object.assign({
        userId,
        img: this.state.file
      }, option);
    Ajax({
      url: '/user/update',
      data: obj,
      success: function(result){
        self.props.onClose(obj);
      },
      error: function(error){
        Toast.info(error||'请求失败');
        self.props.onClose();
      }
    });
  }

  uploadFile = (file) => {
    const self = this;
    var xhr = new XMLHttpRequest();
    var formData = new FormData();
    formData.append('file', file);
    xhr.onerror = function error(e) {
      Toast.info('请求失败');
    };
    xhr.onload = function onload() {
      if (xhr.status < 200 || xhr.status >= 300) {
        Toast.info('请求失败');
      }
      const back = getBody(xhr);
      self.setState({
        file: back.data[0]
      });
    };
    xhr.open('post', backUrl('/common/uploadimage'), true);
    xhr.send(formData);
  }

  onChange = (files, type, index) => {
    console.log(files, type, index);
    const file = files[files.length - 1];
    this.setState({
      files: [file]
    });
    this.uploadFile(file.file);
  }

  render() {
    const { getFieldProps } = this.props.form;
    const { files } = this.state;
    const { phone, nickname, img } = this.props.userData;
    const { imgBaseUrl } = this.props;
    let fileArr = [];
    if(files.length > 0){
      const url = files[0].url;
      fileArr = [{
        url: url.indexOf('base64')>=0?url:imgBaseUrl + url,
        id: 1123
      }]
    }
    return (<div className="updata-user"><List renderHeader={() => (
        <div style={{ position: 'relative' }}>
          修改
          <span
            style={{
              position: 'absolute', right: 3, top: -5,
            }}
            onClick={() => this.props.onClose()}
          >
            <Icon type="cross" />
          </span>
        </div>)}
        className="popup-list"
      >
        <TextareaItem
          {...getFieldProps('nickname', {
            initialValue: nickname
          })}
          title="昵称"
          autoHeight
          labelNumber={5}
        />
        <TextareaItem
          {...getFieldProps('phone', {
            initialValue: phone
          })}
          title="手机号"
          autoHeight
          labelNumber={5}
        />
        <Item extra={<ImagePicker
          files={fileArr}
          onChange={this.onChange}
          onImageClick={(index, fs) => console.log(index, fs)}
          selectable={files.length < 2}
        />}>头像</Item>
        <Button type="primary" style={{margin: '.2rem'}} onClick={() => this.submit()}>提交</Button>
      </List></div>)
  }
}
const BuyModule = createForm()(buyModuleComp);
